package alex.edu;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class StatusesActivity extends Activity {

	/** Called when the activity is first created. */

	ListView StatusesListView;

	public static final int NOTIFICATION_ID = 1;

	ArrayAdapter<Status> adapter;
	ArrayList<Status> statuses = new ArrayList<Status>();
	ArrayList<Status> sublist = new ArrayList<Status>();
	int currentPosition = 0;

	private Status selectedStatus;
	static final private int QUAKE_DIALOG = 1;

	private StatusReceiver receiver;

	@Override
	public void onCreate(Bundle icicle) {
		/*
		 * adjust activty view and it's action
		 */
		super.onCreate(icicle);
		setContentView(R.layout.main);
		Button next = (Button) this.findViewById(R.id.next_button);
		next.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (currentPosition < statuses.size())
					initailzeStatusSubList();
			}
		});
		StatusesListView = (ListView) this
				.findViewById(R.id.earthquakeListView);
		// adjust listview view
		StatusesListView.setBackgroundColor(Color.BLUE);
		View footer = getLayoutInflater().inflate(R.layout.main,
				StatusesListView, false);
		StatusesListView.addFooterView(footer);
		// adjust action on the selected items

		StatusesListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView _av, View _v, int _index,
					long arg3) {
				selectedStatus = statuses.get(_index);
				showDialog(QUAKE_DIALOG);
			}
		});

		// adjust adapter
		int layoutID = android.R.layout.simple_list_item_1;
		adapter = new ArrayAdapter<Status>(this, layoutID, sublist);
		StatusesListView.setAdapter(adapter);

		// register the broadcast receiver
		IntentFilter filter;
		filter = new IntentFilter(StatusService.NEW_STATUS_FOUND);
		receiver = new StatusReceiver();
		registerReceiver(receiver, filter);

		// TO CALL SERVICE
		refreshStatuses();

		// // INITIALZIE GUI FOR THE FIRST FIVE STATUSUES
		// initailzeStatusSubList();
	}

	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
		case (QUAKE_DIALOG):
			LayoutInflater li = LayoutInflater.from(this);
			View quakeDetailsView = li.inflate(R.layout.quake_details, null);
			AlertDialog.Builder quakeDialog = new AlertDialog.Builder(this);
			quakeDialog.setTitle("Quake Time");
			quakeDialog.setView(quakeDetailsView);
			return quakeDialog.create();
		}
		return null;
	}

	@Override
	public void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case (QUAKE_DIALOG):
			SimpleDateFormat sdf;
			sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
			String dateString = sdf.format(selectedStatus.getCreated_at());
			String quakeText = "Status " + selectedStatus.getStatus() + "\n"
					+ selectedStatus.getId() + "\n";
			AlertDialog quakeDialog = (AlertDialog) dialog;
			quakeDialog.setTitle(dateString);
			TextView tv = (TextView) quakeDialog
					.findViewById(R.id.quakeDetailsTextView);
			tv.setText(quakeText);
			break;
		}
	}

	private void initailzeStatusSubList() {
		// sublist= (ArrayList<Status>) statuses.subList(0, 5);
		sublist.removeAll(sublist);
		int i;
		for (i = currentPosition; i < currentPosition + 5
				&& i < statuses.size(); i++) {
			sublist.add(statuses.get(i));
		}
		adapter.notifyDataSetChanged();
		currentPosition = i;
	}

	private void refreshStatuses() {
		startService(new Intent(this, StatusService.class));
	}

	// implements the inner class of the broadcast
	public class StatusReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// initilaze broadcast only one time ?
			// ////////// update list box ////////////////
			// get data from the intent
			// if (arg1.getIntExtra("index", -1) > 0) { // there are new
			// statuses
			User user = new User((Date) arg1
					.getSerializableExtra("user_created_at"), arg1
					.getStringExtra("user_display_name"), arg1
					.getStringExtra("user_first_name"), arg1.getIntExtra(
					"user_id", 0), arg1.getStringExtra("user_last_name"));
			Status status = new Status((Date) arg1
					.getSerializableExtra("created_at"), arg1
					.getStringExtra("status"), arg1.getIntExtra("id", 0), user);
			if (arg1.getIntExtra("server_acc", -1) == 1)
				statuses.add(status); // in case of first time access the
			// server
			else {
				// in case of update
				currentPosition = 0;
				statuses.add(arg1.getIntExtra("index", -1), status);
			}
		}
	}

	@Override
	public void onResume() {
		initailzeStatusSubList();
		super.onResume();
	}

	@Override
	public void onPause() {
		unregisterReceiver(receiver);
		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		int groupId = 0; // Group ID
		int menuItemId = 0;
		int menuItemOrder = Menu.NONE; // order position
		int menuItemText = R.string.send_mail; // item text
		menu.add(groupId, menuItemId, menuItemOrder, menuItemText);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case (0): {
			// refreshStatuses();
			Intent i = new Intent(this, ComposeActivity.class);
			startActivity(i);
			return true;
		}
		}
		return false;
	}

}
